<?php

namespace app\api\controller\bargain;

use app\api\controller\Controller;
use app\api\model\bargain\Task as TaskModel;
use app\api\model\bargain\Setting as SettingModel;
use app\api\model\Goods as GoodsModelc;
use app\api\service\order\Checkout as CheckoutModel;
use app\common\enum\order\OrderSource as OrderSourceEnum;
use think\Db;

class Order extends Controller
{
    /* @var \app\api\model\User $user */
    private $user;

    /**
     * 构造方法
     * @throws \app\common\exception\BaseException
     * @throws \think\exception\DbException
     */
    public function _initialize()
    {
        parent::_initialize();
        // 用户信息
        $this->user = $this->getUser();
    }

    /**
     * 砍价订单结算
     * @return array
     * @throws \app\common\exception\BaseException
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \Exception
     */
    public function checkout()
    {
        // 实例化结算台服务
        $Checkout = new CheckoutModel;
        // 订单结算api参数
        $params = $Checkout->setParam($this->getParam([
            'task_id' => 0
        ]));
        // 获取砍价任务详情
        $task = TaskModel::detail($params['task_id']);
        // 获取砍价商品信息
        $goodsList = $task->getTaskGoods($params['task_id']);
        if ($goodsList === false) {
            return $this->renderError($task->getError());
        }
        // 设置订单来源
        $Checkout->setOrderSource([
            'source' => OrderSourceEnum::BARGAIN,
            'source_id' => $params['task_id'],
        ]);
        // 砍价商品不参与 等级折扣和优惠券折扣
        $Checkout->setCheckoutRule([
            'is_user_grade' => false,
            'is_coupon' => false,
            'is_use_points' => false,
            'is_dealer' => SettingModel::getIsDealer(),
        ]);
        // 获取订单结算信息
        $orderInfo = $Checkout->onCheckout($this->user, $goodsList);
        if ($this->request->isGet()) {
            return $this->renderSuccess($orderInfo);
        }
        //用户被拉黑，不能支付
        if($this->user['is_black'] == 2){
            return $this->renderError('涉嫌违规操作，无法继续操作！');
        }

        //判断是否能购买
//        $checkUserBuy_err = $this->checkUserBuy($task['goods_id'],1,1);
//        if($checkUserBuy_err){
//            return $this->renderError($checkUserBuy_err);
//        }
        // submit：订单结算提交
        if ($Checkout->hasError()) {
            return $this->renderError($Checkout->getError());
        }
        // 创建订单
        if (!$Checkout->createOrder($orderInfo)) {
            return $this->renderError($Checkout->getError() ?: '订单创建失败');
        }
        // 订单创建后将砍价任务结束
        $task->setTaskEnd();
        // 构建微信支付请求
        $payment = $Checkout->onOrderPayment();
        // 支付状态提醒
        $message = ['success' => '支付成功', 'error' => '订单未支付'];
        return $this->renderSuccess([
            'order_id' => $Checkout->model['order_id'],   // 订单id
            'pay_type' => $params['pay_type'],  // 支付方式
            'payment' => $payment               // 微信支付参数
        ], $message);
    }

    /**
     * 订单结算提交的参数
     * @param array $define
     * @return array
     */
    private function getParam($define = [])
    {
        return array_merge($define, $this->request->param());
    }
    /**
     * @param $goods_id
     * @param $goods_num
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\DbException
     * @throws db\exception\DataNotFoundException
     * @throws db\exception\ModelNotFoundException
     * 判断用户能否购买
     */
    private function checkUserBuy($goods_id,$goods_num,$type){
        /*判断此用户能否购买start*/
        $goods = GoodsModelc::detail($goods_id);
        if($goods['buy_number'] > 0){
            //当前商品如果有限购数量
            $order_goods_num = Db::table('yoshop_order_goods')
                ->join('order','order.order_id = yoshop_order_goods.order_id')
                ->where('order.pay_status','=',20)
                ->where('yoshop_order_goods.user_id','=',$this->user['user_id'])
                ->where('order.order_source','=',10)
                ->where('yoshop_order_goods.goods_id','=',$goods_id)
                ->sum('total_num');
            if(($goods_num + $order_goods_num) > $goods['buy_number']){
                if($type == 2){
                    return '很抱歉，商品['.$goods['goods_name'].']限购'.$goods['buy_number'].'次，您已超限';
                }else{
                    return '本商品限购'.$goods['buy_number'].'次，您已超限';
                }
            }
        }
        $buy_grade = $goods['buy_grade'] ? json_decode($goods['buy_grade']) : '';
        //限制会员等级
        if(is_array($buy_grade)){
            if(isset($buy_grade[0])){
                if(intval($buy_grade[0])){
                    //限制会员等级
                    if(!in_array($this->user['grade_id'],$buy_grade)){
                        $user_grade_data = Db::table('yoshop_user_grade')->where('grade_id','in',$buy_grade)->order('weight asc')->find();
                        return '您不是'.$user_grade_data['name'].'，无法下单，请开通再来！';
                    }
                }
            }
        }
        /*判断此用户能否购买end*/

        //限制新用户购买
        if($goods['buy_limit_new'] == 2){
            if(Db::table('yoshop_order')->where('pay_status','=',20)
                ->where('user_id','=',$this->user['user_id'])
                ->where('order_source','=',10)->find()){
                $order_success_num = Db::table('yoshop_order')
                    ->where('pay_status','=',20)
                    ->where('user_id','=',$this->user['user_id'])
                    ->where('order_source','=',10)
                    ->count();
            }else{
                $order_success_num = 0;
            }
            $order_success_num = $order_success_num ? $order_success_num : 0;
            if($order_success_num > 1){
                return '该商品仅限新用户购买！';
            }
        }

        //用户被拉黑，不能支付
        if($this->user['is_black'] == 2){
            return '涉嫌违规操作，无法继续操作！';
        }

    }

    /**
     * 检测用户等级
     */
    public function checkgrade(){
        $goods_id = $this->request->param('goods_id');
        if($goods_id){
            $goods = GoodsModelc::detail($goods_id);
            $buy_grade = $goods['buy_grade'] ? json_decode($goods['buy_grade']) : array();
            $buy_grade = array_filter($buy_grade);
            if(is_array($buy_grade)){
                if(isset($buy_grade[0])){
                    if(intval($buy_grade[0])){
                        //限制会员等级
                        if(!in_array($this->user['grade_id'],$buy_grade)){
                            $user_grade_data = Db::table('yoshop_user_grade')->where('grade_id','in',$buy_grade)->order('weight asc')->find();
                            return $this->renderError('您不是'.$user_grade_data['name'].'，无法下单，请开通再来！');
                        }
                    }
                }
            }
            return $this->renderSuccess('无限制');
        }
    }

}
